import { LowSync, } from 'lowdb'
import { JSONFileSync } from 'lowdb/node'


interface KVData {
    [key: string]: any,
}

export interface KVDataSource {

    put(key: string, value: any): void

    getString(key: string, defaultValue: string): string

    getNumber(key: string, defaultValue: number): number

    getBoolean(key: string, defaultValue: boolean): boolean

}



/**
 * 如果需要一个新数据库文件，可重新new object，通过构造函数传入name
 */
export class LowKVDataSource implements KVDataSource {
    private db

    constructor(name:string){
        this.db = new LowSync<KVData>(new JSONFileSync(name), {})
        this.db.read()
    }



    put(key: string, value: any): void {
        this.db.update((data) => {
            data[key] = value
        })
    }
    
    getString(key: string, defaultValue: string = ""): string {
        try {
            const value = this.db.data[key]
            if (typeof value === "string") {
                return value as string
            } else {
                return defaultValue
            }
        } catch (error) {
            return defaultValue
        }
    }
    getNumber(key: string, defaultValue: number = -1): number {
        try {
            const value = this.db.data[key]
            if (typeof value === "number") {
                return value as number
            } else {
                return defaultValue
            }
        } catch (error) {
            return defaultValue
        }
    }
    getBoolean(key: string, defaultValue: boolean = false): boolean {
        try {
            const value = this.db.data[key]
            if (typeof value === "boolean") {
                return value as boolean
            } else {
                return defaultValue
            }
        } catch (error) {
            return defaultValue
        }
    }

}

/**
 * 提供一个默认实现
 */
export const lowdbDefault = new LowKVDataSource("db.json")